package com.ruoyi.framework.websocket;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringContextUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.websocket.dto.MessageBody;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/message")
@Lazy
public class WebSocketServer {
  /**
   * WebSocketServer 日志控制器
   */
  private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

  /**
   * 默认最多允许同时在线人数100
   */
  public static int socketMaxOnlineCount = 100;

  private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);
  private final TokenService tokenService = SpringContextUtils.getBean(TokenService.class);
  private final RedisCache redisCache = SpringContextUtils.getBean(RedisCache.class);

  /**
   * 连接建立成功调用的方法
   */
  @OnOpen
  public void onOpen(Session session) throws Exception {
    boolean semaphoreFlag = false;
    // 尝试获取信号量
    semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
    if (!semaphoreFlag) {
      // 未获取到信号量
      LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
      WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
      session.close();
    } else {
      String token = session.getRequestParameterMap().get("token").get(0);
      if (token == null || token.isEmpty()) {
        WebSocketUsers.sendMessageToUserByText(session, "token不能为空");
        session.close();
        return;
      }
      // 解析token
      LoginUser loginUser = getLoginUser(token);
      if (loginUser == null) {
        WebSocketUsers.sendMessageToUserByText(session, "token无效");
        session.close();
        return;
      }
      // 添加用户
      WebSocketUsers.put(loginUser.getUserId() + "", session);
      LOGGER.info("\n 建立连接 - {}", session);
      LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
      WebSocketUsers.sendMessageToUserByText(session, "连接成功");
    }
  }

  /**
   * 连接关闭时处理
   */
  @OnClose
  public void onClose(Session session) {
    LOGGER.info("\n 关闭连接 - {}", session);
    // 移除用户
    boolean removeFlag = WebSocketUsers.remove(session.getId());
    if (!removeFlag) {
      // 获取到信号量则需释放
      SemaphoreUtils.release(socketSemaphore);
    }
  }

  /**
   * 抛出异常时处理
   */
  @OnError
  public void onError(Session session, Throwable exception) throws Exception {
    if (session.isOpen()) {
      // 关闭连接
      session.close();
    }
    String sessionId = session.getId();
    LOGGER.info("\n 连接异常 - {}", sessionId);
    LOGGER.info("\n 异常信息 - {}", exception);
    // 移出用户
    WebSocketUsers.remove(sessionId);
    // 获取到信号量则需释放
    SemaphoreUtils.release(socketSemaphore);
  }

  /**
   * 服务器接收到客户端消息时调用的方法
   */
  @OnMessage
  public void onMessage(String message, Session session) {
    MessageBody messageBody = JSONUtil.toBean(message, MessageBody.class);
//    String msg = message.replace("你", "我").replace("吗", "");
    WebSocketUsers.sendMessageToUserByText(session, messageBody);
  }

  public LoginUser getLoginUser(String token) {
    if (StringUtils.isNotEmpty(token)) {
      try {
        Claims claims = tokenService.parseToken(token);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = tokenService.getTokenKey(uuid);
        return redisCache.getCacheObject(userKey);
      } catch (Exception e) {
        LOGGER.error("获取用户信息异常'{}'", e.getMessage());
      }
    }
    return null;
  }
}
